#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author  : config_spider
import json
import math

import scrapy
import re
from apps.tax_policy.tax_policy.items import NetTaxPolicyItem as Item, urllib, time
from apps.tax_policy.tax_policy.spiders.base_spider.base_tax_policy_spider import BaseTaxPolicySpider


class HenanZhumadianPolicy(BaseTaxPolicySpider):
    name = 'henan_zhumadian2_policy'
    
    province = '河南省'
    city = '驻马店市'
    # county = '滑县'
    park = ''

    custom_settings = {
        "DOWNLOAD_TIMEOUT": 60
    }
    headers = {
        "Accept": "application/json, text/javascript, */*; q=0.01",
        "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36",
        # "X-Requested-With": "XMLHttpRequest"
    }

    def start_requests(self):
        for source, county, url in [
            ['驻马店市西平县人民政府', "西平县", "http://www.xiping.gov.cn/portal/zwgk/zfwj/xz/A09030201index_1.htm"],
            ['驻马店市西平县人民政府', "西平县", "http://www.xiping.gov.cn/portal/zwgk/zfwj/xzw/A09030202index_1.htm"],
            ['驻马店市西平县人民政府', "西平县", "http://www.xiping.gov.cn/portal/zwgk/zfwj/xzb/A09030203index_1.htm"],
            ['驻马店市商务局', "", "http://swj.zhumadian.gov.cn/index.php?c=content&a=list&catid=302"],
            ['驻马店市文化广电和旅游局', "", "https://wglj.zhumadian.gov.cn/xinxigongkai/zhengce/guifan/"],
            ['驻马店市人力资源和社会保障局', "", "https://hrss.zhumadian.gov.cn/government_affairs/zc/xzgfxwj"],
        ]:
            item = {'source': source, 'county': county}
            yield scrapy.Request(url, callback=self.parse_list, meta={'item': item}, dont_filter=True)

    def parse_list(self, response, **kwargs):
        prev_item = response.meta.get('item')
        page = response.meta.get('page') or 1
        elem_list = response.xpath(
            "//div[@class='xw' or @class='neirong' or @class='list_02 clearfix']//div//a[@href]/parent::div[string-length(string(.))>=5] |"
            "//div[@class='list_02 clearfix']//a[@href] |"
            "//ul[@class='zfxxgk_zd2']//li//a[@href]/parent::li[string-length(string(.))>=5] |"
            "//div[@class='box-data-right-list' or @class='neirong']//li//a[@href]/parent::li[string-length(string(.))>=5]"
            # "//ul[@class='zhidu']//li//a[@href]/ancestor::li[string-length(string(.))>=10]"
        )
        for elem in elem_list:
            item = Item()
            item['source_url'] = elem.xpath(""".//a/@href""").get() or elem.xpath("""./@href""").get()
            item['source_url'] = response.urljoin(item['source_url'])
            item['publish_date'] = elem.xpath("""string(.)""").get()
            if prev_item is not None:
                for key, value in prev_item.items():
                    item[key] = value
            if not item['source_url']:
                continue
            # if '.htm' not in item['source_url'] and '.shtm' not in item['source_url'] and '.jhtm' not in item['source_url']:
            #     continue
            print(response.url, item['source_url'])
            yield response.follow(item['source_url'], callback=self.parse_detail, meta={'item': item})
        next_url = response.xpath(
            """//a[text()='下页' or ./text()='下页>' or text()='»' or contains(./text(), '下一页') or text()='下一页»']/@href""").get()
        if not next_url:
            next_url = response.xpath(f"""//b[text()='{page}']/following::a/@href""").get()
        if next_url and next_url not in ['javascript:void(0);'] and response.urljoin(next_url) != response.url:
            print(response.url, 'next', next_url)
            yield response.follow(next_url, callback=self.parse_list, meta={'item': prev_item, "page": page + 1})
        else:
            print(response.url, 'not next_url')

    def parse_detail(self, response, **kwargs):
        item = Item() if response.meta.get('item') is None else response.meta.get('item')
        item['title'] = response.xpath("""//*[@class='news_title']/text()""").get() or response.xpath("//title/text()").get()
        item['publish_date'] = response.xpath("""//*[@class='laiyuan']/text()""").re_first(r"\d{4}-\d{2}-\d{2}") or response.xpath(
                ".//*[contains(text(), '发文日期：') or contains(text(), '生成日期：')]/following-sibling::td/text()").re_first(r"\d{4}-\d{2}-\d{2}") or response.xpath(
                ".//*[contains(text(), '发文日期：') or contains(text(), '生成日期：')]/text()").re_first(r"\d{4}-\d{2}-\d{2}")
        item['content'] = response.xpath(""".""").get()
        # item['source'] = self.source
        item['province'] = self.province
        item['city'] = self.city
        # item['county'] = self.county
        item['park'] = self.park
        print(item['publish_date'])
        yield item


if __name__ == "__main__":
    from scrapy import cmdline

    cmdline.execute("scrapy crawl henan_zhumadian2_policy".split())
